const http = require('http');
const fs = require('fs')
const path = require('path')
const url = require('url')
const common = require("./common")

http.createServer(function (request, response) {
    let pathname = url.parse(request.url).pathname ;  //去掉json后面的参数
    pathname = pathname == '/' ? '/hello.html' : pathname;  //默认返回hello.html
    let suffixname = path.extname(pathname)   //得到后缀
    if (pathname != '/favicon.ico') {
        fs.readFile('./static' + pathname, async(err, data) => {
            if (err) {
                response.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
                response.end('page no found');
                return
            } 
            let mime = await common.getFileTrue(suffixname)   //获取后缀对应的Content-Type类型
            response.writeHead(200, { 'Content-Type': mime+';charset="utf-8"' });
            response.end(data);
        })
    }
    
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');